package lc.二叉树;

import utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @description:
 * @author: qian
 * @createDate: 2021/10/11
 */
public class Math111_二叉树的最小深度 {

    // lc.递归
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftMin = minDepth(root.left);
        int rightMin = minDepth(root.right);

        // 右孩子null
        if (root.left == null) {
            return rightMin + 1;
        }
        // 左孩子null
        if (root.right == null) {
            return leftMin + 1;
        }
        // 都不为null;
        return Math.min(leftMin,rightMin) + 1;
    }

    public int minDepth1(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        int res = 0;
        queue.add(root);

        while (!queue.isEmpty()) {

            int size = queue.size();
            res++;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null) {
                    return res;
                }
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }
        return res;
    }

}
